package reactor3;

import org.apache.commons.collections.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: util
 * @description:
 * @author: 周亮亮
 * @create: 2021-11-16 16:07
 **/
public class ReactorBestPractices {
    /**
     * handle
     * testHandle的错误可以一直被抛出到外部，subscribe捕获并处理
     */
    public void outerHandler() {
        testHandle()
                .doOnError(error->{
                    System.out.println("error in do on error " + error);
                    Mono.error(new IllegalArgumentException("exception in doOnError"));
                })
//                .handle((ls, sink)->{
//                    System.out.println("handle method " + ls);
//                })
                .subscribe(result->{
                    System.out.println(result);
                }, error->{
                    System.out.println("error in outerHandler" + error);
                });
    }

    /**
     * 用handle处理数据, 发出处理结果或者抛出错误
     * @return
     */
    public Mono<List<String>> testHandle() {
        List<String> list = new ArrayList<>();

        return Mono.just(list).flatMap(ls->{
            return Mono.just(ls);
        }).handle((ls, sink)->{
            if(CollectionUtils.isEmpty(ls)) {
                sink.error(new IllegalArgumentException("list is empty"));
            } else {
                sink.next(ls);
            }
        });
    }

    public static void main(String[] args) {
        new ReactorBestPractices().outerHandler();
    }
}
